<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="主销售员" name="first"></el-tab-pane>
      <el-tab-pane label="辅销售员" name="second"></el-tab-pane>
    </el-tabs>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="selectPhone">
        <el-input
          v-model="queryParams.selectPhone"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="省级" prop="provinceCode">
        <el-select v-model="queryParams.provinceCode" filterable clearable placeholder="请选择省级地区"
                   @change="getCity(queryParams.provinceCode,'add','query')">
          <el-option
            v-for="dict in provinceOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="市级" prop="cityCode">
        <el-select v-model="queryParams.cityCode" filterable clearable placeholder="请选择市级地区"
                   @change="getArea(queryParams.cityCode,'add','query')">
          <el-option
            v-for="dict in cityOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="区级" prop="areaCode">
        <el-select v-model="queryParams.areaCode" filterable clearable placeholder="请选择区级地区">
          <el-option
            v-for="dict in areaOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择" filterable clearable>
          <el-option
            v-for="dict in stateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['customer:share:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['customer:share:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" align="center" prop="id"/>
      <el-table-column label="客户名称" align="center" prop="name"/>
      <el-table-column label="手机号码" align="center" prop="phone"/>
      <el-table-column label="微信号" align="center" prop="wechat"/>
      <el-table-column label="邮箱" align="center" prop="email"/>
      <el-table-column label="客户规模" align="center" prop="firmSize">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.crm_customer_size" :value="scope.row.firmSize"/>
        </template>
      </el-table-column>
      <el-table-column label="客户类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.crm_customer_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="数据状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.crm_customer_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="过期时间" align="center" prop="updateTime"/>
      <el-table-column label="销售人员" align="center" prop="mainSalerUser.userName"/>
      <el-table-column label="辅销售人员" align="center" prop="assistSalerUser.userName"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleRoam(scope.row)"
          >流转记录
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['customer:share:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['customer:share:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-zoom-in"
            @click="handleLook(scope.row)"
          >查看详细
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-claim"
            @click="handleSign(scope.row)"
          >签约
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-hasPermi="['customer:share:write']"
            @click="handleWrite(scope.row)"
          >写跟进
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-flag"
            v-hasPermi="['customer:share:build']"
            @click="handleBuild(scope.row)"
          >建任务
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleAssign(scope.row)"
            v-hasPermi="['customer:share:assign']"
          >指派
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="form.name" style="width: 400px" placeholder="请输入客户名称"/>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" style="width: 400px" placeholder="请输入手机号码"/>
        </el-form-item>
        <el-form-item label="省级" prop="provinceCode">
          <el-select v-model="form.provinceCode" style="width: 400px" placeholder="请选择省级地区" @change="getCity(form.provinceCode,'add')">
            <el-option
              v-for="dict in provinceOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市级" prop="cityCode">
          <el-select v-model="form.cityCode" style="width: 400px" placeholder="请选择市级地区" @change="getArea(form.cityCode,'add')">
            <el-option
              v-for="dict in cityOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区级" prop="areaCode">
          <el-select v-model="form.areaCode" style="width: 400px" placeholder="请选择区级地区">
            <el-option
              v-for="dict in areaOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="微信号" prop="wechat">
          <el-input v-model="form.wechat" style="width: 400px" placeholder="请输入微信号"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" style="width: 400px" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="客户类型" prop="type">
          <el-select v-model="form.type" style="width: 400px" placeholder="请选择" filterable clearable :disabled="form.id!=null">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="集团客户" prop="pid" v-if="this.form.type==='3'">
          <el-select v-model="form.pid"style="width: 400px"  placeholder="请选择" filterable clearable :disabled="form.id!=null">
            <el-option
              v-for="pCustomer in customerOptions"
              :key="pCustomer.id"
              :label="pCustomer.name"
              :value="pCustomer.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户规模" prop="firmSize">
          <el-select v-model="form.firmSize" style="width: 400px" placeholder="请选择" filterable clearable>
            <el-option
              v-for="dict in sizeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址"/>
        </el-form-item>
        <el-form-item label="企业简介" prop="detail">
          <el-input v-model="form.detail" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 建任务 -->
    <el-dialog :title="titleBuild" :visible.sync="openBuild" width="500px" append-to-body>
      <el-form ref="formBuild" :model="formBuild" :rules="rulesBuild" label-width="80px">
        <el-form-item label="接收人" prop="accepterId">
          <el-select v-model="formBuild.accepterId" placeholder="请选择" filterable clearable>
            <el-option
              v-for="user in userOptions"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="formBuild.type" placeholder="请选择" filterable clearable>
            <el-option
              v-for="dict in taskTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务反馈" prop="feedback">
          <el-input type="textarea" v-model="formBuild.feedback" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formBuild.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormBuild">确 定</el-button>
        <el-button @click="cancelBuild">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 写跟进 -->
    <el-dialog :title="titleWrite" :visible.sync="openWrite" width="500px" append-to-body>
      <el-form ref="formWrite" :model="formWrite" :rules="rulesWrite" label-width="80px">
        <el-form-item label="跟进方式" prop="traceType">
          <el-select v-model="formWrite.traceType" placeholder="请选择" filterable clearable>
            <el-option
              v-for="dict in traceTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跟进时间" prop="createTime">
          <el-date-picker
            v-model="formWrite.createTime"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="请选择"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="跟进内容" prop="traceContent">
          <el-input type="textarea" v-model="formWrite.traceContent" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="图片" prop="tracePic">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileUrl"
            accept=".jpg,.png,.JPG,.PNG,.jpeg"
            :show-file-list="false"
            :headers="headers"
            :on-error="handleUploadError"
            :on-success="handleSuccess"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload">
            <img v-if="formWrite.tracePic" :src="formWrite.tracePic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="业务类型" prop="businessId">
          <el-select v-model="formWrite.businessId" placeholder="请选择" filterable clearable>
            <el-option
              v-for="business in businessList"
              :key="business.id"
              :label="business.name"
              :value="business.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formWrite.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormWrite">确 定</el-button>
        <el-button @click="cancelWrite">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看详细 -->
    <el-dialog :title="titleLook" :visible.sync="openLook" width="600px" append-to-body>
      <el-form ref="form" :model="form"  label-width="80px">
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="form.name" style="width: 400px" placeholder="请输入客户名称" disabled/>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" style="width: 400px" placeholder="请输入手机号码" disabled/>
        </el-form-item>

        <el-form-item label="省级" prop="provinceCode">
          <el-select v-model="form.provinceCode" style="width: 400px" placeholder="请选择省级地区" @change="getCity(form.provinceCode,'add')" disabled>
            <el-option
              v-for="dict in provinceOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市级" prop="cityCode">
          <el-select v-model="form.cityCode" style="width: 400px" placeholder="请选择市级地区" @change="getArea(form.cityCode,'add')" disabled>
            <el-option
              v-for="dict in cityOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区级" prop="areaCode">
          <el-select v-model="form.areaCode" style="width: 400px" placeholder="请选择区级地区" disabled>
            <el-option
              v-for="dict in areaOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" disabled/>
        </el-form-item>
        <el-form-item label="企业简介" prop="detail">
          <el-input v-model="form.detail" type="textarea" placeholder="请输入内容" disabled/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" disabled/>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 显示流转列表 -->
    <el-dialog title="流转记录" :visible.sync="roamOpen" width="1000px" append-to-body>
      <div>
        <el-table :data="roamList" style="margin-top: 10px">
          <el-table-column label="id" align="center" prop="id"/>
          <el-table-column label="客户名称" align="center" prop="crmCustomer.name"/>
          <el-table-column label="操作人" align="center" prop="createBy"/>
          <el-table-column label="操作时间" align="center" prop="createTime"/>
          <el-table-column label="内容" align="center" prop="content"/>
        </el-table>
      </div>
      <pagination
        v-show="roamTotal>0"
        :total="roamTotal"
        :page.sync="queryParamsRoam.pageNum"
        :limit.sync="queryParamsRoam.pageSize"
        @pagination="handleRoam"
      />
    </el-dialog>
    <!-- 指派   -->
    <el-dialog :title="titleAssign" :visible.sync="openAssign" width="500px" append-to-body>
      <el-form ref="formAssign" :model="formAssign" :rules="rulesAssign" label-width="80px">
        <el-form-item label="销售人员" prop="uid">
          <el-select v-model="formAssign.uid" placeholder="请选择" filterable clearable>
            <el-option
              v-for="user in userOptions"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormAssign">确 定</el-button>
        <el-button @click="cancelAssign">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 签约对话框 -->
    <el-dialog :title="signDialog.title" :visible.sync="signDialog.open" width="600px" append-to-body>
      <el-form ref="signForm" :model="signForm" :rules="signDialog.rules" label-width="115px">
        <el-form-item label="签约主体公司" prop="signMainId">
          <el-select v-model="signForm.signMainId" placeholder="请选择签约主体公司" clearable filterable>
            <el-option
              v-for="item in allSignMainList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSignForm">确 定</el-button>
        <el-button @click="cancelSign">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addCustomer,
  delCustomer, dormancyAssign,
  getCustomer, listCustomerNotPage,
  listMarketCustomer, listShareCustomer, shareAssign,
  shareSign,
  updateCustomer
} from "@/api/customer/intentionCustomer";
import {listAreaAll} from "@/api/area/area";
import {addTask} from "@/api/task/task";
import {getUser, getUserListByRoleKey, getUserProfile, listUserNotPage} from "@/api/system/user";
import {addProgess, getBusinessList} from "@/api/progess/progess";
import {getToken} from "@/utils/auth";
import {listTranslog} from "@/api/translog/translog";
import {listAllSignMain} from "@/api/sign_main/signmain";

export default {
  name: "Customer",
  dicts: ['crm_customer_state', 'crm_customer_size', 'crm_customer_type', 'trace_type', 'task_type', 'task_status'],
  data() {
    return {
      // 弹出层标题
      titleAssign: "",
      // 是否显示弹出层
      openAssign: false,
      businessList: [],
      activeName: 'first',
      // 查询参数
      queryParamsRoam: {
        orderByColumn: 'm.create_time',
        isAsc: 'desc',
        pageNum: 1,
        pageSize: 10,
        cid: null,
      },
      roamTotal: 0,
      roamOpen:false,
      roamList:[],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      openWrite: false,
      titleWrite: '',
      // 省级
      provinceOptions: [],
      // 市级
      cityOptions: [],
      // 区级
      areaOptions: [],
      userOptions: [],
      stateOptions: [],
      sizeOptions: [],
      typeOptions: [],
      traceTypeOptions: [],
      taskTypeOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      customerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        selectPhone: null,
        orderByColumn: 'm.create_time',
        isAsc: 'desc',
        pageNum: 1,
        pageSize: 10,
        name: null,
        phone: null,
        rankTag: null,
        status: 5,
        state: null,
        provinceCode: null,
        cityCode: null,
        areaCode: null,
        address: null,
        detail: null,
        wechat: null,
        email: null,
        type: null,
        firmSize: null,
        oper:0
      },
      // 表单参数
      form: {
        mainSalerUser:{}
      },
      // 表单校验
      rules: {
        pid: [
          {required: true, message: "集团客户不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "客户名称不能为空", trigger: "blur"}
        ],
        phone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        provinceCode: [
          {required: true, message: "省级不能为空", trigger: "blur"}
        ],
        address: [
          {required: true, message: "详细地址不能为空", trigger: "blur"}
        ],
        email: [
          {required: false, message: "邮箱地址不能为空", trigger: "blur"},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
        ],
        type: [
          {required: true, message: "客户类型不能为空", trigger: "blur"},
        ],
        firmSize: [
          {required: true, message: "客户规模不能为空", trigger: "blur"},
        ],
      },
      formBuild: {},
      openBuild: false,
      titleBuild: '',
      rulesBuild: {
        accepterId: [
          {required: true, message: "接受人不能为空", trigger: "blur"},
        ],
        feedback: [
          {required: true, message: "任务反馈不能为空", trigger: "blur"},
        ],
        type: [
          {required: true, message: "类型不能为空", trigger: "blur"},
        ],
      },
      // 表单校验
      rulesWrite: {
        businessId: [
          {required: true, message: "业务类型不能为空", trigger: "blur"},
        ],
        createTime: [
          {required: true, message: "跟进时间不能为空", trigger: "blur"},
        ],
        traceType: [
          {required: true, message: "跟进方式不能为空", trigger: "blur"},
        ],
        traceContent: [
          {required: true, message: "跟进内容不能为空", trigger: "blur"},
        ],
      },
      formWrite: {},
      cid: null,
      uid: null,
      titleLook: '',
      openLook: false,
      loginUser:{},
      // 表单校验
      rulesAssign: {
        uid: [
          {required: true, message: "销售人员不能为空", trigger: "blur"},
        ],
      },
      formAssign: {},
      //签约表单、对话框
      signForm: {},
      signDialog: {
        title: "",
        open: false,
        rules: {
          signMainId:[{required: true, message: "签约主体不能为空", trigger: "blur"}],
        },
      },
      // 全签约主体列表
      allSignMainList: [],
    };
  },
  created() {
    this.getBusinessList();
    this.getCustomerList();
    this.getSalesManList();
    this.getUserInfo();
    this.getList();
    this.getProvince()
    this.getDicts("crm_customer_state").then(response => {
      this.stateOptions = response.data;
    });
    this.getDicts("crm_customer_size").then(response => {
      this.sizeOptions = response.data;
    });
    this.getDicts("crm_customer_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("trace_type").then(response => {
      this.traceTypeOptions = response.data;
    });
    this.getDicts("task_type").then(response => {
      this.taskTypeOptions = response.data;
    });
  },
  methods: {
    /** 指派按钮操作 */
    handleAssign(row) {
      this.resetAssign()
      this.openAssign = true;
      this.cid = row.id;
      if (row.mainSalerUser != null) {
        this.titleAssign = "指派人员";
        const id = row.mainSalerUser.userId
        getUser(id).then(response => {
          this.formAssign.userName = response.data.userName;
          this.formAssign.uid = row.mainSalerUser.userId;
        });
      }
    },
    // 表单重置
    resetAssign() {
      this.formAssign = {
        uid: null,
        userName: null
      };
      this.cid = null
      this.resetForm("formAssign");
    },
    // 取消按钮
    cancelAssign() {
      this.openAssign = false;
      this.resetAssign();
    },
    /** 提交按钮 */
    submitFormAssign() {
      this.$refs["formAssign"].validate(valid => {
        if (valid) {
          let data = {
            cid: this.cid,
            uid: this.formAssign.uid,
          }
          shareAssign(data).then(response => {
            this.$modal.msgSuccess("保存成功");
            this.openAssign = false;
            this.getList();
          });
        }
      });
    },
    /** 查询业务类型列表 */
    getBusinessList() {
      getBusinessList().then(response => {
        this.businessList = response.data;
      });
    },
    handleClick(tab, event) {
      if(tab.index==0){
        this.activeName="first"
      }else {
        this.activeName="second"
      }
      this.queryParams.oper = tab.index
      this.getList()
    },
    //打开liuzhuan记录
    handleRoam(val) {
      if(val&&val.id){
        this.cid = val.id
        this.queryParamsRoam.cid = val.id
      }else {
        this.queryParamsRoam.cid=this.cid
      }
      listTranslog(this.queryParamsRoam).then(response => {
        this.roamList = response.rows;
        this.roamTotal = response.total;
        this.roamOpen = true;
      });
    },
    getCustomerList(){
      let query={
        type:"2"
      }
      listCustomerNotPage(query).then(response => {
        this.customerOptions = response.data;
      });
    },
    getUserInfo(){
      getUserProfile().then(response => {
        this.loginUser = response.data;
      });
    },
    /** 查看详细按钮操作 */
    handleLook(row) {
      this.reset();
      const id = row.id
      getCustomer(id).then(response => {
        this.form = response.data;
        this.openLook = true;
        this.titleLook = "详细信息";
        this.getCity(this.form.provinceCode, "edit");
        this.getArea(this.form.cityCode, "edit");
      });
    },
    /** 签约按钮操作 */
    handleSign(row) {
      if (row.provinceCode == null || row.provinceCode === '') {
        this.$modal.msgError("请先完善客户信息！");
        return;
      }
      this.signForm.id = row.id;
      this.signForm.status = "2";
      // this.$modal.confirm('是否确认签约客户编号为"' + row.id + '"的数据项？').then(function() {
      //   let data = {
      //     status: "2",
      //     id: row.id
      //   }
      //   return signCustomer(data);
      // }).then(() => {
      //   this.$modal.msgSuccess("签约成功！");
      //   this.getList();
      // }).catch(() => {});
      this.getSignMainList();
      this.signDialog.open = true;
      this.signDialog.title = "签约客户表单"
    },
    // 获取签约主体列表
    getSignMainList(){
      let q= {};
      listAllSignMain(q).then(response => {
        this.allSignMainList = response;
      });
    },
    /** 签约表单提交 */
    submitSignForm() {
      this.$refs["signForm"].validate(valid => {
        if (valid) {
          shareSign(this.signForm).then(response => {
            this.$modal.msgSuccess("签约成功");
            this.signDialog.open = false;
            this.getList();
          });
        }
      });
    },
    /** 签约表单取消 */
    cancelSign() {
      this.signDialog.open = false;
      this.signForm.signMainId = null;
      this.signForm.id = null;
      this.signForm.status = null;
    },


    // 图片上传前校检格式和大小
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    // 图片文件个数超出
    handleExceed() {
      this.$message.error(`只允许上传单个文件`);
    },
    handleSuccess(res, file) {
      this.$message.success("上传成功");
      this.formWrite.tracePic = res.url;
    },
    // 图片上传失败
    handleUploadError(err) {
      this.$message.error("上传失败, 请重试");
    },
    /** 提交按钮 */
    submitFormWrite() {
      this.$refs["formWrite"].validate(valid => {
        if (valid) {
          this.formWrite.uid = this.loginUser.userId
          this.formWrite.cid = this.cid
          this.formWrite.assignerId = this.loginUser.userId
          addProgess(this.formWrite).then(response => {
            this.$modal.msgSuccess("保存成功");
            this.openWrite = false;
            this.getList();
          });
        }
      });
    },
    // 取消按钮
    cancelWrite() {
      this.openWrite = false;
      this.resetWrite();
    },
    // 表单重置
    resetWrite() {
      this.formWrite = {
        businessId:null,
        id: null,
        cid: null,
        assignerId: null,
        uid: null,
        traceType: null,
        traceContent: null,
        tracePic: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.uid = null
      this.resetForm("formWrite");
    },
    /** 写跟进按钮操作 */
    handleWrite(row) {
      this.resetWrite();
      this.cid = row.id
      this.openWrite = true;
      this.titleWrite = "我的跟进";
    },
    /** 查询销售列表 */
    getSalesManList(){
      var array = [];
      array.push("sales");
      getUserListByRoleKey(array).then(response => {
        if(response.code === 200){
          this.userOptions = response.data;
        }
      });
    },
    // 表单重置
    resetBuild() {
      this.formBuild = {
        id: null,
        cid: null,
        assignerId: null,
        accepterId: null,
        feedback: null,
        status: null,
        type: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.uid = null
      this.resetForm("formBuild");
    },
    /** 提交按钮 */
    submitFormBuild() {
      this.$refs["formBuild"].validate(valid => {
        if (valid) {
          this.formBuild.cid = this.cid
          addTask(this.formBuild).then(response => {
            this.$modal.msgSuccess("保存成功");
            this.openBuild = false;
            this.getList();
          });
        }
      });
    },
    // 取消按钮
    cancelBuild() {
      this.openBuild = false;
      this.resetBuild();
    },
    /** 建任务按钮操作 */
    handleBuild(row) {
      this.resetBuild();
      this.cid = row.id
      this.openBuild = true;
      this.titleBuild = "创建任务";
    },
    //获取区级地区
    getArea(val, type, oper) {
      this.areaOptions = []
      if (type !== "edit" && oper !== "query") {
        this.$set(this.form, 'areaCode', '');
      }
      if (oper === "query") {
        this.$set(this.queryParams, 'areaCode', '');
      }
      const data = {
        parentId: val,
        isEnabled: 1
      }
      listAreaAll(data).then(response => {
        this.areaOptions = response.data;
      });
    },
    //获取市级地区
    getCity(val, type, oper) {
      this.cityOptions = []
      this.areaOptions = []
      if (type !== "edit" && oper !== "query") {
        this.$set(this.form, 'cityCode', '');
        this.$set(this.form, 'areaCode', '');
      }
      if (oper === "query") {
        this.$set(this.queryParams, 'cityCode', '');
        this.$set(this.queryParams, 'areaCode', '');
      }
      let data = {
        parentId: val,
        isEnabled: 1
      }
      listAreaAll(data).then(response => {
        this.cityOptions = response.data;
      });
    },
    //获取省级
    getProvince() {
      const data = {
        parentId: 0,
        isEnabled: 1
      }
      listAreaAll(data).then(response => {
        this.provinceOptions = response.data;
      });
    },
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      listShareCustomer(this.queryParams).then(response => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        phone: null,
        rankTag: null,
        status: "0",
        state: null,
        provinceCode: null,
        cityCode: null,
        areaCode: null,
        address: null,
        detail: null,
        wechat: null,
        email: null,
        type: null,
        firmSize: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCustomer(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户";
        this.getCity(this.form.provinceCode, "edit");
        this.getArea(this.form.cityCode, "edit");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除客户编号为"' + ids + '"的数据项？').then(function () {
        return delCustomer(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('customer/customer/export', {
        ...this.queryParams
      }, `customer_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #1890ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
